package fr.dauphine.spring.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;

public abstract class DAO {
	
	protected void fillStatement(Connection conn, PreparedStatement st, List<Object> param) throws Exception {
		int i=0;
		if (param != null) {
			Iterator<Object> iter = param.iterator();
			while (iter.hasNext()) {
				Object p = iter.next();
				if (p == null) {
					st.setNull(++i,java.sql.Types.VARCHAR);
				} 
				else {
					st.setObject(++i,p);
				}
			}
		}
	}
	
	/**
	 * Remplit un statement de mise a jour à partir d'une requête et d'une liste de parametres
	 * @param conn
	 * @param query
	 * @param param
	 * @return
	 * @throws Exception
	 */
	private PreparedStatement getStatement(Connection conn, String query, List<Object> param) throws Exception {
		PreparedStatement st = conn.prepareStatement(query);
		this.fillStatement(conn, st, param);	
		return st;
	}

	/**
	 * Execute une requete de selection
	 * @param conn
	 * @param query
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public PreparedStatement executeQuery(Connection conn, String query, List<Object> param) throws Exception {
		return this.getStatement(conn, query, param);		
	}

	/**
	 * Execute une requete de mise a jour
	 * @param conn
	 * @param update
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public int executeUpdate(Connection conn, String update, List<Object> param) throws Exception {
		PreparedStatement st = this.getStatement(conn, update, param);
		int count = st.executeUpdate();
		st.close();
		return count;
	}


}
